#!/bin/bash

#!/sbin/runscript                                                                       

ipset_cmd=/usr/sbin/ipset
iptables_cmd=/sbin/iptables

depend() {
        need localmount
        after modules
}

start() {
        cd $ipsets_dir
        for site in $ipsets; do
            bzcat ${site}.bz2 | $ipset_cmd -R
        done
        bzcat NOCLIP.bz2 | $ipset_cmd -R

        $iptables_cmd -A INPUT -p tcp --sport 80 --tcp-flags FIN,SYN,RST,ACK SYN,ACK -m state --state ESTABLISHED -m set --match-set NOCLIP src -j ZHANG

        $iptables_cmd -A INPUT -p tcp --sport 80 -m state --state ESTABLISHED -m gfw -j LOG --log-level info --log-prefix "gfw: "

        $iptables_cmd -A INPUT -p udp --sport 53 -m state --state ESTABLISHED -m gfw -j DROP
}

stop() {
       rules=`$iptables_cmd -L INPUT | sed '1,2d' | grep -n gfw | awk -F: '{print  $1}' | sort -r`
       for h in $rules; do
           $iptables_cmd -D INPUT $h
       done

       rules=`$iptables_cmd -L INPUT | sed '1,2d' | grep -n ZHANG | awk -F: '{print  $1}' | sort -r`
       for h in $rules; do
           $iptables_cmd -D INPUT $h
       done

       $ipset_cmd -X NOCLIP
       for site in $ipsets; do
           $ipset_cmd -X $site
       done
}
